<?php

require_once 'Pipes/Database/RelationshipTable.php';
require_once 'Pipes/FileSystem/Model/Finder.php';
require_once 'Pipes/Generator/Create/Controller.php';
require_once 'Pipes/Generator/Create/Model.php';
require_once 'Pipes/Generator/Create/ModelList.php';
require_once 'Pipes/Generator/Create/Model/Mapper.php';
require_once 'Pipes/Generator/Create/Model/Meta.php';
require_once 'Pipes/Generator/Create/View.php';
require_once 'PipesImpl/Config.php';

class Pipes_Generator_Create
{
    private $_creators = array();
    private $_default_options = array(
        'with' => array()
    );
    private $_options = array();
    private $_relatedObjects = array();
    private $_config = null;

    public function __construct(PipesImpl_Config $config, $projectPath, array $options = array()) {
        $this->_config = $config;

        $this->_creators = array(
            new Pipes_Generator_Create_Controller($projectPath),
            new Pipes_Generator_Create_Model($projectPath),
            new Pipes_Generator_Create_ModelList($projectPath),
            new Pipes_Generator_Create_Model_Mapper($projectPath),
            new Pipes_Generator_Create_Model_Meta($projectPath),
            new Pipes_Generator_Create_View($projectPath)
        );

        $this->_options = array_merge($this->_default_options, $options);
        $this->_relatedObjects = $this->_options['with'];
        foreach ($this->_options['with'] as $key => $value) {
            $converter = new Pipes_Value_Template_CamelCapsToDatabase($value);
            $this->_options['with'][$key] = $converter->value;
        }
        
        if (count($this->_relatedObjects) > 0) {
            $relationshipOptions = $this->_options;
            unset($relationshipOptions['with']);
            $this->_relationshipCreator = new Pipes_Generator_Create($config, $projectPath, $relationshipOptions);
            $this->_relationshipFinder = new Pipes_FileSystem_Model_Finder($config);
        }
    }
    
    public function create($name) {
        foreach ($this->_creators as $creator) {
            $creator->create($name, $this->_options);
        }

        foreach ($this->_relatedObjects as $related) {
            // create model if we can't find it
            try {
                $this->_relationshipFinder->find($related);
            } catch (Pipes_Exception $e) {
                $this->_relationshipCreator->create($related);
            }

            // create relationship table if it doesn't exist
            $relationshipTable = new Pipes_Database_RelationshipTable($this->_config, $name, $related);
            if (!$relationshipTable->exists()) {
                $relationshipTable->create();
            }
        }
    }
}
